<template>
  <div>
    <!-- 联系人卡片 -->
    <van-contact-card
      :type="cardType"
      :name="currentContact.name"
      :tel="currentContact.tel"
      @click="showList = true"
    />

    <!-- 联系人列表 -->
    <van-popup v-model="showList" position="bottom">
      <van-contact-list
        v-model="chosenContactId"
        :list="list"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
      />
    </van-popup>

    <!-- 联系人编辑 -->
    <van-popup v-model="showEdit" position="bottom">
      <van-contact-edit
        :tel-validator="()=>true"
        :contact-info="editingContact"
        :is-edit="isEdit"
        @save="onSave"
        @delete="onDelete"
      />
    </van-popup>
  </div>
</template>

<script>
  import Vue from "vue";
  import { ContactCard, ContactList, ContactEdit ,Popup} from 'vant';
  import {mapState,mapGetters,mapActions,mapMutations} from "vuex";
  Vue.use(ContactCard);
  Vue.use(ContactList);
  Vue.use(ContactEdit);
  Vue.use(Popup);

  export default {
    name:"contact",
    data() {
      return {
        showList: false,//联系人列表是否顯示
        showEdit: false,//联系人编辑是否顯示
        isEdit: false,//控制编辑页的删除按钮是否显示
      };
    },
    computed: {
      ...mapState(["editingContact","list"]),
      ...mapGetters(["cardType","currentContact"]),
      chosenContactId:{
        get(){return this.$store.state.chosenContactId},
        set(val){
          this.updateChosenContactId(val)
        }
      }
    },
    methods: {
      ...mapActions(["getList","updateList","addList",
        "delList","updateEditingContact","updateChosenContactId"]),
      onAdd() {
        this.updateEditingContact({})
        this.isEdit = false;
        this.showEdit = true;
      },
      onEdit(item) {
        this.isEdit = true;
        this.showEdit = true;
        this.updateEditingContact(item)
      },
      async onSave(info) {
        this.showEdit = false;
        this.showList = false;
        if (this.isEdit) {
          await this.updateList(info)
          //...后续流程必须在action中的代码完成之后才能调用 那么前面必须要卡流程
        } else {
          await this.addList(info)
          //....后续流程必须在action中的代码完成之后才能调用 那么前面必须要卡流程
        }
      },
      async onDelete({id}) {
        this.showEdit = false;
        await this.delList(id)
      },
      onSelect() {
        this.showList = false;
      },
    },
    async created(){
       try{
         await this.getList()  //true:代表是否开启loading
         //....后续流程必须在action中的代码完成之后才能调用 那么前面必须要卡流程
       }catch (e) {

       }


    }
  };
</script>

<style scoped>

</style>
